package com.wwu.common;

import javax.xml.bind.Marshaller;
import java.lang.reflect.Field;

/**
 * Java对象转换为XML时，若属性值为null也生成对应空标签
 * @param null:
 * @return: null
 * @Author: 一蓑烟雨
 * @Date: 2022/3/16 0016 下午 13:48
 */
public class MarshallerListener extends Marshaller.Listener  {
	public static final String BLANK_CHAR = "";

	@Override
	public void beforeMarshal(Object source) {
		super.beforeMarshal(source);
		Field[] fields = source.getClass().getDeclaredFields();
		for (Field f : fields) {
			f.setAccessible(true);
			//获取字段上注解<pre name="code" class="java">
			try {
				if (f.getType() == String.class && f.get(source) == null) {
					f.set(source, BLANK_CHAR);
				}
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
	}
}
